package br.com.sgc.dao;

import java.util.List;

import javax.ejb.Stateless;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import br.com.sgc.entities.geral.Cliente;
import br.com.sgc.entities.geral.PessoaFisica;
import br.com.sgc.enuns.TipoOrdenacao;

@Stateless
public class ClienteDao extends GenericDao<Cliente> {

	private static final long serialVersionUID = -5749622469681797809L;
	
	public Long count(Cliente modelClass, Long clinicaId) {
		Long size = 0L;
		Criteria criteria = getCriteria(Cliente.class);
		createCriteriaRestrictions(modelClass, clinicaId, criteria);
		criteria.setProjection(Projections.rowCount());
		size = (Long) criteria.uniqueResult();
        return size;
	}
	
	public List<Cliente> findAll(Cliente modelClass, Long clinicaId, Integer startPage, Integer maxPage, String orderField, Boolean initializeDependecies) {
		return findAll(modelClass, clinicaId, startPage, maxPage, orderField, initializeDependecies, TipoOrdenacao.ASC);
	}
	
	@SuppressWarnings("unchecked")
	public List<Cliente> findAll(Cliente modelClass, Long clinicaId, Integer startPage, Integer maxPage, String orderField, Boolean initializeDependecies, TipoOrdenacao tipoOrdenacao){
		
		Criteria criteria = getCriteria(Cliente.class);
		criteria.setFirstResult(startPage);
		criteria.setMaxResults(maxPage);
		
		createCriteriaRestrictions(modelClass, clinicaId, criteria);
		
		if(orderField != null && !orderField.trim().equals("")) {
			if(tipoOrdenacao == TipoOrdenacao.ASC){
				criteria.addOrder(Order.asc(orderField));
			} else {
				criteria.addOrder(Order.desc(orderField));
			}
			
		}
		
		List<Cliente> lista = criteria.list();
		if(initializeDependecies) {
			for(Cliente t : lista){
				t.getPessoa().toString();
			}
		}
			
		return lista;
	}

	private void createCriteriaRestrictions(Cliente modelClass, Long clinicaId, Criteria criteria) {
		if(modelClass != null){
			if(modelClass.getClinica() != null && modelClass.getClinica().getId() != null){
				criteria.add(Restrictions.eq("clinica.id", modelClass.getClinica().getId()));
			}
			
			if(modelClass.getPessoa() instanceof PessoaFisica){
				criteria.createAlias("pessoa", "pessoa");
				if(modelClass.getPessoa().getDisplayNome() != null && !modelClass.getPessoa().getDisplayNome().isEmpty()){
					criteria.add(Restrictions.ilike("pessoa.nome", ((PessoaFisica)modelClass.getPessoa()).getNome(), MatchMode.ANYWHERE));
				} 
				
				if(modelClass.getPessoa().getDisplayDocumento() != null && !modelClass.getPessoa().getDisplayDocumento().isEmpty()){
					criteria.add(Restrictions.eq("pessoa.cpf", ((PessoaFisica)modelClass.getPessoa()).getCpf()));
				}
				
			}
		}
	}

	
	

}
